<script setup lang="ts">
import { orderStateActions, pageUrl } from '@/utils/constants'
import { receiveOrderById } from '@/api/order'
import type { paymentTradeInfo } from '@/types/order'

const props = defineProps<{
  id: number | string
  status: number
  className?: string
  paymentTradeInfo: paymentTradeInfo
}>()

//确认收货
const onReceive = () => {
  if (props.paymentTradeInfo && props.paymentTradeInfo.source === 'miniapp') {
    miniAppReceive()
  } else {
    normalReceive()
  }
}

const normalReceive = () => {
  uni.showModal({
    title: '提示',
    content: '为保障您的权益，请收到货并确认无误后，再确认收货',
    showCancel: true,
    success: async ({ confirm, cancel }) => {
      if (confirm) {
        return doReceive()
      }
    },
  })
}

// 小程序收货组件
const miniAppReceive = () => {
  if ((wx as any).openBusinessView) {
    ;(wx as any).openBusinessView({
      businessType: 'weappOrderConfirm',
      extraData: {
        merchant_id: props.paymentTradeInfo.wxpay_mch_id,
        merchant_trade_no: props.paymentTradeInfo.out_trade_no,
        transaction_id: props.paymentTradeInfo.trade_no,
      },
      success(event: any) {
        console.log('e1', event)
        if (event.extraData.status === 'success') {
          console.log('用户确认收货')
          return doReceive()
        }
        if (event.extraData.status === 'fail') {
          // 用户确认收货失败
          return uni.showToast({
            title: '确认收货失败!',
            icon: 'none',
          })
        }
        if (event.extraData.status === 'cancel') {
          // 用户取消
          return uni.showToast({
            title: '取消确认收货!',
            icon: 'none',
          })
        }
      },
      fail(faild: any) {
        console.log(faild)
        // 用户确认收货失败
        return uni.showToast({
          title: '确认收货失败!',
          icon: 'none',
        })
      },
    })
  } else {
    //引导用户升级微信版本
    uni.showToast({
      title: '当前微信版本过低,请升级微信版本后再使用该功能',
      duration: 3000,
      icon: 'none',
    })
  }
}

const doReceive = async () => {
  console.log('请求api收货接口')
  const res = await receiveOrderById(Number(props.id))
  if (res) {
    uni.showToast({
      title: '确认收货成功',
      icon: 'success',
      mask: true,
    })
    //跳转
    uni.redirectTo({
      url: `${pageUrl['order-receive']}?id=${props.id}`,
    })
  }
}
</script>

<template>
  <view v-if="orderStateActions.receiveble.includes($props.status)">
    <view @tap="onReceive" :class="props.className"> 确认收货 </view>
  </view>
</template>

<style>
.button {
  width: 150rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 20rpx;
  border-radius: 60rpx;
  border: 1rpx solid #ccc;
  font-size: 26rpx;
  color: #444;
}

.secondary {
  color: #ff5f3c;
  border-color: #ff5f3c;
}

.primary {
  color: #fff;
  background-color: #ff5f3c;
}
</style>
